package com.wrt.sps.shiro;

import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.wrt.sps.mgt.entity.Permission;
import com.wrt.sps.mgt.entity.Role;
import com.wrt.sps.mgt.entity.User;
import com.wrt.sps.mgt.service.UserService;

/**
 * shiro 配置
 * 
 * @author 文瑞涛
 * @date 2021年1月6日 下午10:04:05
 */
@Component
public class CustomRealm extends AuthorizingRealm {

	@Autowired
	private UserService userService;

	/**
	 * 权限配置类
	 * 
	 * @Param principalCollection
	 * @Return AuthorizationInfo
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		// 获取登录用户名
		User user = (User) principalCollection.getPrimaryPrincipal();
		// 添加角色和权限
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		Role role = user.getRole();
		if (null != role) {
			// 添加角色
			simpleAuthorizationInfo.addRole(user.getRole().getRoleName());
			if (CollectionUtils.isNotEmpty(role.getPermissions())) {
				// 添加权限
				for (Permission permissions : role.getPermissions()) {
					simpleAuthorizationInfo.addStringPermission(permissions.getPermissionName());
				}
			}
		}
		return simpleAuthorizationInfo;
	}

	/**
	 * 
	 * 认证配置类
	 * 
	 * @Param authenticationToken
	 * @Return AuthenticationInfo
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
			throws AuthenticationException {
		if (null == authenticationToken.getPrincipal()) {
			return null;
		}
		// 获取用户信息
		String name = authenticationToken.getPrincipal().toString();
		User user = userService.findUserByLoginName(name);
		if (user == null) {
			// 这里返回后会报出对应异常
			return null;
		} else if (!user.getValidFlag().booleanValue()) {
			throw new AuthenticationException(Boolean.FALSE.toString());
		} else {
			// 这里验证authenticationToken和simpleAuthenticationInfo的信息
			return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
		}
	}
}
